#include <gtest/gtest.h>

#include "helper/resource/OpenableResource.h"

class OpenOnceDB  : public helper::resource::OpenableResource<std::error_code> {
public:
	~OpenOnceDB()	override {
	}
	bool exists() const{
		return _exists;
	}
	std::error_code destroy() override {
		_exists = false;
		return std::error_code();
	}
protected:
	std::error_code _open() override {
		_exists = true;
		return std::error_code();
	}
	std::error_code _close() override {
		return std::error_code();
	}
private:
	bool _exists = false;
};

TEST(OpenOnceDBTest, test){
	OpenOnceDB db;
	ASSERT_TRUE(!db.exists());
	ASSERT_TRUE(!db.isOpened());

	ASSERT_EQ(std::error_code(), db.open());
	ASSERT_TRUE(db.isOpened());
	ASSERT_TRUE(db.exists());

	ASSERT_NE(std::error_code(), db.open());

	ASSERT_EQ(std::error_code(), db.close());
	ASSERT_TRUE(!db.isOpened());
	ASSERT_TRUE(db.exists());

	ASSERT_NE(std::error_code(), db.close());

	ASSERT_EQ(std::error_code(), db.destroy());

	ASSERT_TRUE(!db.exists());
}


#include "helper/resource/ReopenableResource.h"

class ReopenableDB : public helper::resource::ReopenableResource<std::error_code> {
public:
	~ReopenableDB()	override {}

	bool exists() const{
		return _exists;
	}
	std::error_code destroy() override {
		_exists = false;
		return std::error_code();
	}
protected:
	std::error_code _open() override {
		_exists = true;
		return std::error_code();
	}
	std::error_code _close() override {
		return std::error_code();
	}
private:
	bool _exists = false;

};


TEST(ReopenableDB, test){
	ReopenableDB db;
	ASSERT_TRUE(!db.exists());
	ASSERT_TRUE(!db.isOpened());

	ASSERT_EQ(std::error_code(), db.open());
	ASSERT_TRUE(db.isOpened());
	ASSERT_TRUE(db.exists());

	ASSERT_EQ(std::error_code(), db.open());

	ASSERT_EQ(std::error_code(), db.close());
	ASSERT_TRUE(!db.isOpened());
	ASSERT_TRUE(db.exists());

	ASSERT_EQ(std::error_code(), db.close());

	ASSERT_EQ(std::error_code(), db.destroy());

	ASSERT_TRUE(!db.exists());
}
